// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <pollux/functions/sparksql/aggregates/central_moments_aggregate.h>

#include <limits>
#include <pollux/functions/lib/aggregates/central_moments_aggregates_base.h>

namespace kumo::pollux::functions::aggregate::sparksql {
    namespace {
        // Calculate the skewness value from m2, count and m3.
        //
        // @tparam nullOnDivideByZero If true, return NULL instead of NaN when dividing
        // by zero during the calculating.
        template<bool nullOnDivideByZero>
        struct SkewnessResultAccessor {
            static bool hasResult(const CentralMomentsAccumulator &accumulator) {
                if constexpr (nullOnDivideByZero) {
                    return accumulator.count() >= 1 && accumulator.m2() != 0;
                }
                return accumulator.count() >= 1;
            }

            static double result(const CentralMomentsAccumulator &accumulator) {
                if (accumulator.m2() == 0) {
                    POLLUX_CHECK(
                        !nullOnDivideByZero,
                        "NaN is returned only when m2 is 0 and nullOnDivideByZero is false.");
                    return std::numeric_limits<double>::quiet_NaN();
                }
                return std::sqrt(accumulator.count()) * accumulator.m3() /
                       std::pow(accumulator.m2(), 1.5);
            }
        };

        // Calculate the kurtosis value from m2, count and m4.
        //
        // @tparam nullOnDivideByZero If true, return NULL instead of NaN when dividing
        // by zero during the calculating.
        template<bool nullOnDivideByZero>
        struct KurtosisResultAccessor {
            static bool hasResult(const CentralMomentsAccumulator &accumulator) {
                if constexpr (nullOnDivideByZero) {
                    return accumulator.count() >= 1 && accumulator.m2() != 0;
                }
                return accumulator.count() >= 1;
            }

            static double result(const CentralMomentsAccumulator &accumulator) {
                if (accumulator.m2() == 0) {
                    POLLUX_CHECK(
                        !nullOnDivideByZero,
                        "NaN is returned only when m2 is 0 and nullOnDivideByZero is false.");
                    return std::numeric_limits<double>::quiet_NaN();
                }
                double count = accumulator.count();
                double m2 = accumulator.m2();
                double m4 = accumulator.m4();
                return count * m4 / (m2 * m2) - 3.0;
            }
        };

        template<template <bool> typename TResultAccessor>
        exec::AggregateRegistrationResult registerCentralMoments(
            const std::string &name,
            bool withCompanionFunctions,
            bool overwrite) {
            std::vector<std::shared_ptr<exec::AggregateFunctionSignature> > signatures;
            signatures.push_back(
                exec::AggregateFunctionSignatureBuilder()
                .returnType("double")
                .intermediateType(CentralMomentsIntermediateResult::type())
                .argumentType("double")
                .build());

            return exec::registerAggregateFunction(
                name,
                std::move(signatures),
                [name](
            core::AggregationNode::Step step,
            const std::vector<TypePtr> &argTypes,
            const TypePtr &resultType,
            const core::QueryConfig &config) -> std::unique_ptr<exec::Aggregate> {
                    POLLUX_CHECK_EQ(argTypes.size(), 1, "{} takes only one argument", name);
                    const auto &inputType = argTypes[0];
                    if (exec::isRawInput(step)) {
                        POLLUX_USER_CHECK_EQ(
                            inputType->kind(),
                            TypeKind::DOUBLE,
                            "Unsupported input type: {}. "
                            "Expected DOUBLE.",
                            inputType->toString());
                        if (config.sparkLegacyStatisticalAggregate()) {
                            return std::make_unique<
                                CentralMomentsAggregatesBase<double, TResultAccessor<false> > >(
                                resultType);
                        }
                        return std::make_unique<
                            CentralMomentsAggregatesBase<double, TResultAccessor<true> > >(
                            resultType);
                    }
                    checkAccumulatorRowType(
                        inputType,
                        "Input type for final aggregation must be "
                        "(count:bigint, m1:double, m2:double, m3:double, m4:double) struct");
                    if (config.sparkLegacyStatisticalAggregate()) {
                        return std::make_unique<CentralMomentsAggregatesBase<
                            int64_t /*unused*/,
                            TResultAccessor<false> > >(resultType);
                    }
                    return std::make_unique<
                        CentralMomentsAggregatesBase<double, TResultAccessor<true> > >(
                        resultType);
                },
                withCompanionFunctions,
                overwrite);
        }
    } // namespace

    void registerCentralMomentsAggregate(
        const std::string &prefix,
        bool withCompanionFunctions,
        bool overwrite) {
        registerCentralMoments<SkewnessResultAccessor>(
            prefix + "skewness", withCompanionFunctions, overwrite);
        registerCentralMoments<KurtosisResultAccessor>(
            prefix + "kurtosis", withCompanionFunctions, overwrite);
    }
} // namespace kumo::pollux::functions::aggregate::sparksql
